package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.exception.BusinessException;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.constant.RedisConstants.*;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MRS
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getShopTypeList() {

        //先从Redis从查询数据,存在则返回
        List<String> shopTypeJsonList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        List<ShopType> shopTypeList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(shopTypeJsonList)) {
            shopTypeList = shopTypeJsonList.stream().map(json-> JSONUtil.toBean(json, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }

        //从数据库查询
        shopTypeList = lambdaQuery().orderByAsc(ShopType::getSort).list();

        Optional.ofNullable(shopTypeList).<BusinessException>orElseThrow(()-> {
            throw new BusinessException("商铺类型列表不存在");
        });

        //从数据库查询到的数据存入Redis中返回
        List<String> shopTypeListJson = shopTypeList.stream()
                .map(shopType -> JSONUtil.toJsonStr(shopType))
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE_KEY, shopTypeListJson);
        stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY, CACHE_NULL_TTL, TimeUnit.HOURS);
        return Result.ok(shopTypeList);
    }
}
